import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：徐志荣
 * @Date：2023/5/23 17:01
 */

class Message{
    public String from;
    public String to;
    public String message;
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
 //   private List<Message> messageList = new ArrayList<>();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //把body中内容读取,解析成Message对象
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        //此处通过简单粗暴的方式来完成保存
       // messageList.add(message);
        save(message);
        resp.setStatus(200);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //数据是json,字符集utf8
        resp.setContentType("application/json;charset=utf8");
        //这个方法同时完成了,把java对象转成json字符串和把这个字符串写到响应对象中
       // objectMapper.writeValue(resp.getWriter(),messageList);
        List<Message> messageList = null;
        try {
            messageList = load();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String jsonResp = objectMapper.writeValueAsString(messageList);
        System.out.println(jsonResp);

        //把这个字符串写回到响应body中
        resp.getWriter().write(jsonResp);
    }




    //提供一对方法
    //往数据库中存一条消息
    private void save(Message message){
        //JDBC操作
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //1.建立连接
             connection = DBUtil.getConnection();
            //2.构建SQL语句
            String sql = "insert into message values(?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,message.from);
            statement.setString(2,message.to);
            statement.setString(3,message.message);
            //3.
            statement.executeUpdate();


        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //4.关闭连接
            DBUtil.close(connection,statement,null);
        }
    }

    //从数据库取所有消息
    private List<Message> load() throws SQLException {
        List<Message> messageList = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            //1.和数据库建立连接
            connection = DBUtil.getConnection();
            //2.构造SQL
            String sql = "select * from message";
             statement = connection.prepareStatement(sql);
            //3.执行SQL
             resultSet = statement.executeQuery();
            //4.遍历结果集合
            while(resultSet.next()){
                Message message = new Message();
                message.from =resultSet.getString("from");
                message.to =resultSet.getString("to");
                message.message =resultSet.getString("message");
                messageList.add(message);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //5.
            DBUtil.close(connection,statement,resultSet);
        }
        return messageList;
    }



    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    //删除最后一条数据
    private void deleteTail( List<Message> messageList) {

        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //1.建立连接
            connection = DBUtil.getConnection();
            //2.构建SQL语句
            String sql = "delete from message where `from` = ?";
            statement = connection.prepareStatement(sql);
            //获取最后一条数据的 from 数据
            Message message = messageList.get(messageList.size()-1);
            String str = message.from;
            statement.setString(1,str);
            //3.
            statement.executeUpdate();


        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //4.关闭连接
            DBUtil.close(connection,statement,null);
        }
    }


}
